<?php

/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/3/31
 * Time: 13:40
 */

namespace Admin\Controller;


use Bbs\Api\BbsMemberApi;
use Bbs\Api\FilterKeyWordsApi;
use Bbs\Api\ForumAttachmentApi;
use Bbs\Api\ForumForumApi;
use Bbs\Api\ForumPostApi;
use Bbs\Api\ForumThreadApi;
use Bbs\Api\ForumUserAdmingroupApi;
use Bbs\Model\ForumPostModel;
use Ucenter\Api\MemberApi;
use Ucenter\Api\MemberExpApi;

class BbsThreadController extends AdminController{

    protected function _initialize() {
        parent::_initialize();
        $this->check(UID);
    }
    //帖子重新统计
    public function count(){

        $r = apiCall(ForumThreadApi::QUERY_NO_PAGING,array(array('status'=>0),'dateline desc','tid'));
        // dump($r);exit;
        if($r['status']){
            foreach ($r['info'] as $v) {
                $tid   = $v['tid'];
                $count = 0;
                //统计回复
                $res = apiCall(ForumPostApi::COUNT,array(array('tid'=>$tid)));
                // dump($res);
                if($res['status']){
                    if(null !==$res['info']) $count = $res['info'];
                    if($v['replies'] != $count){
                        apiCall(ForumThreadApi::SAVE,array(array('tid'=>$tid),array('replies'=>$count)));
                    }
                }
                //TODO 统计其他
            }
            $this->success('统计回复成功');
        }else{
            $this->error($r['info']);
        }
    }
    //用户权限检查
    private function check($uid){
        $map = array(
            'uid' => $uid,
        );
        $result = apiCall(ForumUserAdmingroupApi::GET_INFO,array($map));
        // dump($result);exit;
        if($result['status']){
            if(empty($result['info']) || (!in_array(intval($result['info']['adminid']), array(1,2)))){
                $this -> error("该用户非管理组");
            }
        }else{
            $this -> error($result['info']);
        }
    }
    public function index(){
        $fid       = I('fid',0);        //板块
        $status    = I('status',-2);    //1审核 0正常 -1删除
        $page_no   = I('p',1);
        $page_size = I('page_size',10);
        // $position  = I('position',0);   //热门？精选？
        $stick     = I('stick',-1);     //置顶
        $digest    = I('digest',-1);    //精华
        $page_no   = intval($page_no);
        $page_size = intval($page_size);
        $this -> assign('status',$status);
        $this -> assign('fid',$fid);
        $this -> assign('stick',$stick);
        $this -> assign('digest',$digest);

        $result = apiCall(ForumForumApi::QUERY_NO_PAGING);
        if(!$result['status']) $this -> error('系统故障：forum get tree');
        // dump($result['info']);exit;
        $forumall = array();
        foreach ($result['info'] as $v) {
            $forumall[$v['fid']] = $v;
        }
        $this -> assign('forumall',$forumall);

        // $result = apiCall(ForumForumApi::QUERY_WITH_CHILD);
        // if(!$result['status']) $this -> error('系统故障：forum get tree');
        // $forum = $result['info'];
        $forum = array();
        foreach ($forumall as $v) {
            if($v['fup'] == 0 ){
                $v['child'] = array();
                $forum[$v['fid']]=$v;
            }
        }
        foreach ($forumall as $v) {
            if($v['fup'] != 0 ) $forum[$v['fup']]['child'][$v['fid']]=$v;
        }
        // var_dump($forum);exit;
        $this -> assign('forum',$forum);

        $map = array();
        if(-2!=$status) $map['status'] = $status;
        if(-1!=$stick)  $map['stick']  = $stick;
        if(-1!=$digest) $map['digest'] = $digest;
        if($fid){
            $ids =  apiCall(ForumForumApi::GET_IDS,array($fid));
            $map['fid'] = array('in',$ids);
        }

        $params = $map;
        if($fid) $params['fid'] = $fid;
        $page = array(
            'curpage' => $page_no,
            'size'    => $page_size,
        );
        $order = 'dateline desc';
        $result = apiCall(ForumThreadApi::QUERY_WITH_COUNT2,array($map,$page,$order,$params));
        if($result['status']){
            $list = $result['info']['list'];
            foreach ($list as &$v) {
                $r = apiCall(MemberApi::GET_INFO,[['uid'=>$v['author_id']]]);
                if($r['status']){
                    $v['author'] = $r['info']['nickname'];
                }
            }
            $this -> assign('list',$list);
            $this -> assign('show',$result['info']['show']);
        }else{
            $this -> error($result['info']);
        }

        $this -> display();
    }

    public function add(){

        if(IS_GET) {
            $map = array();
            $field = "fid,name";
            $result = apiCall(ForumForumApi::QUERY_NO_PAGING, array($map, false, $field));
            if ($result['status']) {
                $this->assign('forum', $result['info']);
            } else {
                $this->error($result['info']);
            }

            $this->display();
        }else{
            $fid = I('post.fid','');
            $subject = I('post.subject','');
            $message = I('post.message','');
            $img = I('post.img','');
            if($fid == '' || $fid <= 0){
                $this -> error('版块选择参数错误');
            }
            $img = explode(',',$img);
            array_pop($img);
            $typeid = 0;
            $author_id = UID;
            $author = "";
            $result = apiCall(MemberApi::GET_INFO,array(array('uid'=>UID)));
            //$result = apiCall(BbsMemberApi::GET_INFO,array(UID));
            if($result['status']){
                $author = $result['info']['nickname'];
            }else{
                $this -> error($result['info']);
            }

            //关键词过滤
            $subject = $this->filter($subject);
            $message = $this->filter($message);

            $now = time();
            $ip = 0;
            if(!empty($_SERVER['REMOTE_ADDR'])){
                $ip = $_SERVER['REMOTE_ADDR'];
            }

            $thread_entity = array(
                'fid' => $fid,
                'typeid' => $typeid,
                'author' => $author,
                'author_id' => $author_id,
                'subject' => $subject,
                'dateline' => $now,
                'views' => 0,
                'replies' => 0,
                'digest' => 0,
                'stick' => 0,
                'status' => 1,
                'likes' => 0,
            );
            $post_entity = array(
                'author' => $author,
                'author_id' => $author_id,
                'subject' => $subject,
                'dateline' => $now,
                'message' => $message,
                'useip' => ip2long($ip),
                'invisible' => 0,//初始未通过审核
                'status' => 1,
                'comment' => 0,
                'position' => 0,
                'fid' => $fid,
            );

            $result = apiCall(ForumThreadApi::ADD_THREAD,array($thread_entity,$post_entity));
            if($result['status']){
                $tid = $result['info']['tid'];
                $pid = $result['info']['pid'];

                //添加附件
                if($img !== ""){
                    $dataList = array();
                    $i = 0;
                    foreach($img as $v){
                        $dataList[$i] = array(
                            'tid' => $tid,
                            'pid' => $pid,
                            'uid' => $author_id,
                            'aid' => $v,
                        );
                        $i++;
                    }
                    if(is_array($dataList) && count($dataList)>=1){
                        $result = apiCall(ForumAttachmentApi::ADD_ALL,array($dataList));
                    }
                }
                if($result['status']){
                    //改变版块中主题数量、帖子数量以及最后发表人
                    $result = apiCall(ForumForumApi::UPDATE,array($fid,$author,1));
                    if($result['status']){
                        //发布帖子+50分 +1经验
                        apiCall(MemberApi::RAISE_SCORE,array($author_id,50));
                        apiCall(MemberExpApi::EXP_INC,array($author_id,10));
                        $this -> success("发表成功！",U('Admin/BbsThread/index'));
                    }else{
                        $this -> error($result['info']);
                    }

                }else{
                    $this -> error($result['info']);
                }

            }else{
                $this -> error($result['info']);
            }
        }

    }

    public function putIndex(){
        $tid = I('post.tid','');
        $show = I('get.show',-1,'int');
        if($show ==-1){
            $this->error('参数错误');
        }
        if($tid === '' || $tid <= 0){
            $this -> error('参数错误');
        }
        $map = array(
            'tid' => $tid,
        );
        $entity = array(
            'position' => $show==1?1:0,
            'update_time' => time(),
        );
        $result = apiCall(ForumThreadApi::SAVE,array($map,$entity));
        if($result['status']){
            $msg = $show==1?'设置首页显示成功':'取消首页显示成功';
            $this -> success($msg,U('Admin/BbsThread/index'));
        }else{
            $this -> error($result['info']);
        }
    }

    //单个置顶 去顶
    public function stick(){
        $tid = I('tid','');
        $stick_value = I('stick_value','');
        if($tid == '' || $stick_value == '' || $tid <= 0 || !in_array($stick_value,array(0,1))){
            $this -> error('参数错误');
        }
        $result = apiCall(ForumThreadApi::STICK,array(UID,$tid,$stick_value));
        if($result['status']){
            $this -> success($result['info']);
        }else{
            $this -> error($result['info']);
        }
    }

    //单个-1删除(默认)·0审核·1重审
    public function delete(){
        $tid    = I('tid',0,'int');
        $status = I('get.status',-1);
        if(!in_array($status,array(-1,0,1))) $this -> error("参数错误");
        $result = apiCall(ForumThreadApi::SAVE,array(array('tid'=>$tid),array('status'=>$status)));
        if($result['status']){
            $this -> success("操作成功!");
        }else{
            $this -> error($result['info']);
        }

    }
    //批量-1删除(默认)·0审核·1重审
    public function delete_all(){
        $tids   = I('ids','');
        $status = I('get.status',-1);
        if($tids == '' || count($tids) == 0){
            $this -> success('操作成功');
        }
        if(!in_array($status,array(-1,0,1))) $this -> error("参数错误");
        $result = apiCall(ForumThreadApi::SAVE,array(array('tid'=>array('in',$tids)),array('status'=>$status)));
        if($result['status']){
            $this -> success("操作成功");
        }else{
            $this -> error($result['info']);
        }
    }
    //单个加精 去精
    public function digest(){
        $tid = I('tid','');
        $digest_value = I('digest_value','');
        if($tid == '' || $digest_value == '' || $tid <=0 || !in_array($digest_value,array(0,1))){
            $this -> error('参数错误');
        }
        $result = apiCall(ForumThreadApi::DIGEST,array(UID,$tid,$digest_value));
        if($result['status']){
            $this -> success($result['info']);
        }else{
            $this -> error($result['info']);
        }
    }

    //查看
    public function view(){

        $tid = I('tid',0,'int');
        if($tid == '' || $tid <= 0) $this -> error('参数错误');
        //取forum_thread中信息
        $map = array(
            'tid' => $tid,
        );
        $result = apiCall(ForumThreadApi::GET_INFO,array($map));
        if($result['status']){
            if(is_null($result['info'])) $this -> error('该帖不存在');
        }else{
            $this -> error($result['info']);
        }
        $fid = $result['info']['fid'];
        $author_id = $result['info']['author_id'];
        $this -> assign('thread_info',$result['info']);
        //取forum_forum中信息
        $map = array(
            'fid' => $fid,
        );
        $result = apiCall(ForumForumApi::GET_INFO,array($map));
        if(!$result['status']){
            $this -> error($result['info']);
        }
        $this -> assign('forum_info',$result['info']);
        //取forum_post中信息
        // $map = array(
        //     'tid' => $tid,
        //     'position' => 0,
        // );
        // $result = apiCall(ForumPostApi::GET_INFO,array($map));
        // if($result['status']){
        //     if(is_null($result['info'])){
        //         $this -> error('不存在相应帖子');
        //     }
        // }else{
        //     $this -> error($result['info']);
        // }
        // $pid = $result['info']['pid'];
        // $this -> assign('post_info',$result['info']);
        //取forum_attachment中信息
        $map = array(
            'tid' => $tid,
            'pid' => 0,
            'uid' => $author_id,
        );
        $result = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map));
        if(!$result['status']){
            $this -> error($result['info']);
        }
        $this -> assign('attachment_info',$result['info']);

        $this -> display();
    }

    public function pass(){
        $tid = I('post.tid','');
        if($tid == '' || $tid <= 0) $this -> error('参数错误');
        $map = [
            'tid' => $tid,
        ];
        $result = apiCall(ForumThreadApi::SAVE,[$map,['status'=>0]]);
        if($result['status']){
            $this -> success('审核通过');
        }else{
            $this -> error($result['info']);
        }
    }

    /**
     * 关键词过滤
     */
    private function filter($posts){
        $result = apiCall(FilterKeyWordsApi::FILTER,[$posts]);
        return $result['info'];
    }

}